package com.apes.scm.masterdata.product.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.model.ProductGroup;
import com.apes.scm.masterdata.product.repository.ProductGroupRepository;
import com.apes.scm.masterdata.product.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 功能：商品组 Service
 *
 * @author HuJianlin
 * @create 2018-03-15 14:35
 */
@Service("productGroupService")
public class ProductGroupService extends DomainService {

    @Autowired
    ProductGroupRepository productGroupRepository;

    public ProductGroup save(SimpleRequest request) {
        ProductGroup productGroup = request.getO(ProductGroup.class);
        return productGroupRepository.saveAndFlush(productGroup);
    }

    public String delete(SimpleRequest request) {
        String id = request.get("id");
        Integer versions = request.get("version");
        ProductGroup productGroup = productGroupRepository.findOne(id);

        if (productGroup == null) throw new RuntimeException("商品组【"+ id +"】在系统中不存在。");
        if (productGroup.getVersion() != versions) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        productGroupRepository.delete(productGroup);
        return "删除成功";
    }

    /**
     * 功能：查询
     *
     * @param request
     */
    public Page<ProductGroup> findAll(SimpleRequest request) {
        List<Map> filters = request.get("condition");
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        return productGroupRepository.findAll(JpaDsl.toCriteria(filters),PageRequest.of(request.get("page"), request.get("size"),sort));
    }

    private ProductGroup findByProductId(SimpleRequest request){
        Product product = SpringManager.getBean(ProductRepository.class).findOne(request.getJO().getString("productId"));
        return product.getProductGroup();
    }
}
